package com.iflytek.autofly.setting.biz.base;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.iflytek.autofly.setting.R;
import com.iflytek.autofly.setting.widget.InnerListView;
import com.iflytek.autofly.setting.widget.LeftPannelButton;
import com.iflytek.autofly.setting.widget.MyViewPager;
import com.iflytek.sunflower.FlowerCollector;

import java.util.ArrayList;

/**
 * <b>Description: </b>分页显示fragment的activity<br/>
 * <b>Change History:</b><br/>
 * <table border="1">
 * <tr>
 * <td><b>user</b></td>
 * <td><b>date</b></td>
 * <td><b>time</b></td>
 * <td><b>reason</b></td>
 * </tr>
 * <tr>
 * <td>JunLuan@iflytek.com</td>
 * <td>2015年6月26日</td>
 * <td>下午6:20:42</td>
 * <td>创建此文件</td>
 * </tr>
 * </table>
 *
 * @author JunLuan@iflytek.com
 */
public abstract class TabFragmentActicity extends BaseFragmentActivity {
    private static final java.lang.String TAG = "TabFragmentActicity";
    private ArrayList<FragmentUnit> mFragmentUnits = new ArrayList<FragmentUnit>();
    private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
    private MyViewPager mViewPager;
    // 当前fragment的index
    private int mCurrentIndex = -1;
    private InnerListView mLeftButtonLv;
    private SpAdpt<ViewHolder, LeftPannelButtonBean> mSpAdpt;
    private OnItemClickListener mItemClickListener;
    private ScrollView mLeftSv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);
        initView();
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLeftButtonLv.setItemChecked(mViewPager.getCurrentItem(), true);
        FlowerCollector.onResume(getApplicationContext());
    }

    @Override
    protected void onPause() {
        super.onPause();
        FlowerCollector.onPause(getApplicationContext());
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // 处理有按钮的旋转动作
        int index = mCurrentIndex;
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_DPAD_RIGHT:
            case KeyEvent.KEYCODE_DPAD_DOWN:
                if (event.getAction() == KeyEvent.ACTION_UP) {
                    index++;
                    if (index < mFragments.size()) {
                        FlowerCollector.onEvent(getApplicationContext(), getLeftButtonName(index), "DPAD");
                        switchToFragment(index);
                    }
                }
                return true;
            case KeyEvent.KEYCODE_DPAD_LEFT:
            case KeyEvent.KEYCODE_DPAD_UP:
                if (event.getAction() == KeyEvent.ACTION_UP) {
                    index--;
                    if (index >= 0) {
                        FlowerCollector.onEvent(getApplicationContext(), getLeftButtonName(index), "DPAD");
                        switchToFragment(index);
                    }
                }
                return true;
            default:
                return super.dispatchKeyEvent(event);
        }
    }

    /**
     * setTabs:将每个tab页添加到fragmentUnits中. <br/>
     *
     * @param fragmentUnits tab页的队列
     */
    abstract protected void setTabs(ArrayList<FragmentUnit> fragmentUnits);

    /**
     * init:初始化操作. <br/>
     */
    abstract protected void init();

    /**
     * switchToFragment:切换到某tab页. <br/>
     *
     * @param index tab页的索引
     */
    protected void switchToFragment(int index) {
        int size = mFragments.size();
        if (index < 0 | index >= size) {
            return;
        }

        if (mCurrentIndex != index) {
            mCurrentIndex = index;
            mLeftButtonLv.setItemChecked(mCurrentIndex, true);

            if (mCurrentIndex == size - 1) {
                mLeftSv.smoothScrollBy(0, (int) getResources().getDimension(R.dimen.main_left_button_height));
            }
            if (mCurrentIndex == 0) {
                mLeftSv.smoothScrollBy(0, (int) -getResources().getDimension(R.dimen.main_left_button_height));
            }
            mViewPager.setCurrentItem(index, false);
            if (mFragmentUnits != null) {
                BaseFragment f = (BaseFragment) mFragments.get(mViewPager.getCurrentItem());
                if (f != null) {
                    //f.collapseAll();
                    f.callRenew();
                }
            }
        }
    }

    private void initView() {

        setTabs(mFragmentUnits);

        mLeftButtonLv = (InnerListView) findViewById(R.id.main_left_listview);
        mSpAdpt = new SpAdpt<>(this, new ViewHolder(), R.layout.left_pannel_button_item);

        for (FragmentUnit u : mFragmentUnits) {
            if (u.fragment != null) {
                int id = mSpAdpt.getCount();
                mSpAdpt.addItem(new LeftPannelButtonBean(u.name, id));
                mFragments.add(u.fragment);
            }
        }
        mLeftButtonLv.setAdapter(mSpAdpt);
        mLeftButtonLv.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String name = getLeftButtonName(position);
                        FlowerCollector.onEvent(getApplicationContext(), name, "click");
                        switchToFragment(position);
                        if (mItemClickListener != null) {
                            mItemClickListener.onClick(position);
                        }
                    }
                }
        );
        mLeftSv = (ScrollView) findViewById(R.id.main_left_scrollview);
        mLeftSv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                adjustButtonView(mLeftSv);
                return false;
            }
        });

        mViewPager = (MyViewPager) findViewById(R.id.viewPager);

        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setPagingEnabled(false);

        mViewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(), mFragments));

        if (mSpAdpt.getCount() > 0) {
            mLeftButtonLv.setItemChecked(0, true);
        }
    }

    protected String getLeftButtonName(int position) {
        if (position >= 0 && position < mFragmentUnits.size()) {
            FragmentUnit u = mFragmentUnits.get(position);
            return u.name;
        }
        return "";
    }

    void adjustButtonView(ScrollView scrollView) {
        LinearLayout bottom = (LinearLayout) findViewById(R.id.main_left_bottom_fg_ll);
        LinearLayout top = (LinearLayout) findViewById(R.id.main_left_top_fg_ll);
        if (scrollView.canScrollVertically(-1)) {
            if (top.getVisibility() != View.VISIBLE) {
                top.setVisibility(View.VISIBLE);
            }
        } else {
            if (top.getVisibility() != View.GONE) {
                top.setVisibility(View.GONE);
            }
        }
        if (scrollView.canScrollVertically(1)) {
            if (bottom.getVisibility() != View.VISIBLE) {
                bottom.setVisibility(View.VISIBLE);
            }
        } else {
            if (bottom.getVisibility() != View.GONE) {
                bottom.setVisibility(View.GONE);
            }
        }
    }

    protected ICommand getCommand(int index) {
        Fragment f = mFragments.get(index);
        if (f instanceof ICommand) {
            return (ICommand) f;
        }
        return null;
    }

    public void setOnItemClickListener(OnItemClickListener l) {
        mItemClickListener = l;
    }

    public interface OnItemClickListener {
        void onClick(int position);
    }

    class LeftPannelButtonBean extends SpAdptBean {
        String text;

        public LeftPannelButtonBean(String text, int id) {
            super(id);
            this.text = text;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }
    }

    class ViewHolder extends SpAdprViewHolder {
        LeftPannelButton spRadioButton;

        @Override
        public void initView(View v) {
            spRadioButton = (LeftPannelButton) v.findViewById(R.id.sp_radio_button);
        }

        @Override
        public void updateView(SpAdptBean b) {
            LeftPannelButtonBean bean = (LeftPannelButtonBean) b;
            spRadioButton.setText(bean.getText());
        }

        @Override
        public void setStatus(int status) {
        }

        @Override
        public SpAdprViewHolder newInstance() {
            return new ViewHolder();
        }
    }

    /**
     * <b>Description: </b>tab页的保存内容<br/>
     * <b>Change History:</b><br/>
     * <table border="1">
     * <tr>
     * <td><b>user</b></td>
     * <td><b>date</b></td>
     * <td><b>time</b></td>
     * <td><b>reason</b></td>
     * </tr>
     * <tr>
     * <td>JunLuan@iflytek.com</td>
     * <td>2015年6月26日</td>
     * <td>下午6:21:25</td>
     * <td>创建此文件</td>
     * </tr>
     * </table>
     *
     * @author JunLuan@iflytek.com
     */
    public class FragmentUnit {
        Fragment fragment;
        String name;

        /**
         * Creates a new instance of FragmentUnit.
         *
         * @param fragment fragment
         * @param name     fragment对于按钮的显示内容
         */
        public FragmentUnit(Fragment fragment, String name) {
            this.fragment = fragment;
            this.name = name;
            if (name == null) {
                this.name = "";
            }
        }
    }

}
